package com.yc.vote.servlet;

import com.yc.common.bean.Result;
import com.yc.common.biz.BizException;
import com.yc.common.servlet.BaseServlet;
import com.yc.vote.entity.Items;
import com.yc.vote.entity.Vote;
import com.yc.vote.mapper.VoteMapper;
import com.yc.vote.service.impl.VoteServiceImpl;
import com.yc.vote.util.MyBatisHelper;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现一个Servlet 响应多个请求
 */
@WebServlet("/vote/*") // * 表示 0~n 字符 用于匹配多个地址
public class VoteServlet extends BaseServlet {
    VoteServiceImpl voteService = new VoteServiceImpl();
    // 要把 protected 改成 public
    // /vote/save.s
    public Result save(HttpServletRequest request, HttpServletResponse response){

        Vote vote = new Vote();
        vote.setVname(request.getParameter("vname"));
        vote.setVtype(request.getParameter("vtype"));
        vote.setItems(new ArrayList<>());

        String[] inames = request.getParameterValues("iname");
        if (inames!=null){
            for (String iname : inames){
                Items items = new Items();
                items.setIname(iname);
                vote.getItems().add(items);
            }
        }
        try {
            voteService.add(vote);
            return Result.success("保存成功", null);
        } catch (BizException e){
            e.printStackTrace();
            return Result.failure(e.getMessage(), null);
        }

    }

    public Vote queryById(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        System.out.println(id);
        return MyBatisHelper.query(session -> {
            VoteMapper voteMapper = session.getMapper(VoteMapper.class);
            return voteMapper.selectById(id);
        });
    }

    public List<Vote> query(HttpServletRequest request, HttpServletResponse response){
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int ipage = Integer.valueOf(page);
        int isize = Integer.valueOf(size);
        return voteService.queryAll(ipage, isize);
    }
}
